package com.mar.tech.unify.handler;

import com.mar.tech.unify.bean.Result;
import com.mar.tech.unify.http.ExtHttpStatus;
import com.mar.tech.unify.spi.FailureHandler;
import io.vertx.core.http.HttpMethod;
import io.vertx.ext.web.RoutingContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Description: 失败处理 .<br>
 *
 * @author m-xy
 *   Created By 2020/1/7 12:11
 */
public class ResultFailureHandler implements FailureHandler {
  private final static Logger logger = LoggerFactory.getLogger(ResultFailureHandler.class);

  @Override
  public void handle(RoutingContext context) {
    if (context.statusCode() == ExtHttpStatus.SC_RATE_LIMIT) {
      Result.failed(context, context.statusCode(), context.failure().getMessage());
      return;
    }
    StringBuilder logBuilder = new StringBuilder();
    logBuilder.append("\n");
    logBuilder.append(context.request().method().toString());
    logBuilder.append(" 请求:");
    logBuilder.append(context.request().absoluteURI());
    logBuilder.append(" -- 响应码:");
    logBuilder.append(context.statusCode());
    if (HttpMethod.POST.equals(context.request().method())) {
      logBuilder.append("\n");
      logBuilder.append(context.getBodyAsString());
    }
    logger.error(logBuilder.toString(), context.failure());
    Result.failed(context, context.statusCode(), context.failure().getMessage());
  }
}
